import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { ThrottlerGuard } from '@nestjs/throttler';
import config from '~/config';

import { AppController } from './app.controller';

//提供者
import { AllExceptionsFilter } from './common/filters/any-exception.filter';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { IdempotenceInterceptor } from './common/interceptors/idempotence.interceptor';
import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';

//基础模块
import { SharedModule } from '~/shared/shared.module';
import { ToolsModule } from '~/modules/tools/tools.module';

//业务模块
import { BusinessModule } from '~/modules/business/business.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      expandVariables: true, //启用环境变量扩展，http://${APP_IP}:${APP_PORT}
      // 指定多个 env 文件时，第一个优先级最高
      envFilePath: [`.env.${process.env.NODE_ENV}`, '.env'],
      load: [...Object.values(config)],
    }),
    //基础依赖模块
    SharedModule,
    ToolsModule,
    //业务模块
    BusinessModule,
  ],
  controllers: [AppController],
  providers: [
    //自定义异常过滤器
    { provide: APP_FILTER, useClass: AllExceptionsFilter },
    // 自定义响应拦截器
    { provide: APP_INTERCEPTOR, useClass: TransformInterceptor },
    //全局请求超时拦截器
    {
      provide: APP_INTERCEPTOR,
      useFactory: () => new TimeoutInterceptor(15 * 1000),
    },
    //请求日志拦截
    { provide: APP_INTERCEPTOR, useClass: LoggingInterceptor },
    //全局幂等性拦截器，防止重复提交请求
    { provide: APP_INTERCEPTOR, useClass: IdempotenceInterceptor },
    //启用请求频率限制守卫
    { provide: APP_GUARD, useClass: ThrottlerGuard },
  ],
})
export class AppModule {}
